package com.itheima.question.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.itheima.PageVo;
import com.itheima.admin.dto.PageDto;
import com.itheima.admin.dto.QuestionDto;
import com.itheima.admin.pojo.Question;
import com.itheima.admin.pojo.Role;
import com.itheima.admin.vo.QuestionVo;
import com.itheima.admin.vo.RoleVo;
import com.itheima.question.mapper.QuestionMapper;
import com.itheima.question.service.IQuestionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public QuestionDto queryQuestionById(String id) {
        Question question = questionMapper.selectById(id);
        QuestionDto questionDto = new QuestionDto();
        BeanUtils.copyProperties(question,questionDto);
        return questionDto;
    }

    @Override
    public boolean addQuestion(QuestionDto questionDto) {
        Question question = new Question();
        BeanUtils.copyProperties(questionDto,question);
        return questionMapper.insert(question)>0;
    }

    @Override
    public PageVo<QuestionVo> queryByPage(PageDto pageDto) {
        IPage<Question> page = new Page<>(pageDto.getCurrentPage(),pageDto.getPageSize());

        QueryWrapper<Question> queryWrapper = null;
        if(pageDto.getQueryString() != null){
            queryWrapper = new QueryWrapper<>();
//            queryWrapper.like("name",pageDto.getQueryString());
        }

        IPage<Question> roleIPage = questionMapper.selectPage(page, queryWrapper);


        List<QuestionVo> collect = getQuestionVos(roleIPage.getRecords());
        return new PageVo<QuestionVo>(collect,(int)roleIPage.getTotal());
    }

    @Override
    public boolean deleteById(String id) {
        int i = questionMapper.deleteById(id);
        return i>0;
    }

    //List<Role>  ===>  List<RoleVo>
    private List<QuestionVo> getQuestionVos(List<Question> roleIPage) {
        if(roleIPage==null){
            return new ArrayList<>();
        }
        return roleIPage.stream().map(
                role -> {
                    QuestionVo questionVo = new QuestionVo();
                    BeanUtils.copyProperties(role, questionVo);
                    return questionVo;
                }
        ).collect(Collectors.toList());
    }
}
